package com.example.dps;

import java.text.DecimalFormat;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import com.downpayment.dps.R;



public class ViewSavingsActivity extends Activity{
	
	String tag = "ViewSavingsActivity";
	
	DBHelper dbhelper;
	AccountDBHelper accountDBHelper;
	WebHelper webHelper;
	HistoryHelper historyHelper;
	TipsDBHelper tipsDBHelper;
	
	DecimalFormat formatter = new DecimalFormat("#,###,###");
	
	/**Layout containing the Tips Table **/
	TableLayout tipsTable = null;
	
	/** ID of current layout (R.layout.X) **/
	int layoutID = 0;
	
	/** rectangle containing the bounds of the button last clicked **/
	private Rect rect;
	
	
	/** status code from the last yodlee request **/
	int statusCode = 0;
	
	/** amount saved **/
	int savedTotal = 0;
	
	/** percent of goal saved **/
	double percentTotal = 0;
	
	
	/** this activities task that animates the house **/
	AsyncTask animateHouseTask;
	
	
	/*
	final static int SELECT_MODE_DIALOG = 1;
	final static int LOGIN_DIALOG = 2;
	final static int MANUAL_ADD_MONEY_DIALOG = 3;
	 */
	
	
	
	@Override
	public void onPause(){
		super.onPause();
		
		if(this.animateHouseTask != null)
			this.animateHouseTask.cancel(true);
		
		this.initHouseAnimation();
	}
	
	
	/**
	 * creates the option menu. (logout/settings/etc)
	 */
	@Override
	public void onBackPressed(){
		
		if(this.layoutID == R.layout.history_layout){
			this.layoutID = R.layout.view_savings_activity;
			changeToLayout(R.layout.view_savings_activity);
		}
		else{
			
			Intent intent = new Intent(ViewSavingsActivity.this, MainActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			
		}
		
	}
	
	@Override
	 public void onWindowFocusChanged(boolean hasFocus) {
		  // TODO Auto-generated method stub
		  super.onWindowFocusChanged(hasFocus);
		  //if(this.layoutID == R.layout.view_savings_activity) animateHouse();
	  
	 }
	
	@Override
	protected Dialog onCreateDialog(int id) {
		AlertDialog.Builder builder = null;
		LayoutInflater inflater = null;
		
		switch (id) {
		case Constants.LOGIN_DIALOG:
			builder = new AlertDialog.Builder(this);
		    // Get the layout inflater
		    inflater = this.getLayoutInflater();

		    // Inflate and set the layout for the dialog
		    // Pass null as the parent view because its going in the dialog layout
		    builder.setView(inflater.inflate(R.layout.login_layout, null))
		    // Add action buttons
		           .setPositiveButton("Login", new DialogInterface.OnClickListener() {
		               @Override
		               public void onClick(DialogInterface dialog, int id) {
		            	   
		            	   EditText usernameText = (EditText)((AlertDialog)dialog).findViewById(R.id.loginUsernameValue);
		            	   EditText passwordText = (EditText)((AlertDialog)dialog).findViewById(R.id.loginPasswordValue);
		            	   
		            	   if(usernameText != null && passwordText != null){
		            		   String username = usernameText.getText().toString();
		            		   String password = passwordText.getText().toString();
		            		   
		            		   //Log.e("atasdf", username + password);
		            		   
		            		   ViewSavingsActivity.this.webHelper.login(username,password, true);
		            	   }
		            	   else{
		            		   Toast.makeText(ViewSavingsActivity.this, "Please enter your username and password", Toast.LENGTH_LONG).show();
		            	   }
		            	   //dialog.
		            	   
		               }
		           })
		           .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
		               public void onClick(DialogInterface dialog, int id) {
		                   //LoginDialogFragment.this.getDialog().cancel();
		            	   ViewSavingsActivity.this.webHelper.logout();
		            	   
		            	   Intent intent = new Intent(ViewSavingsActivity.this, MainActivity.class);
		            	   //intent.putExtra("START_TAB", "view_savings");
		            	   //startActivity(intent);
		            	   //finish();
		               }
		           });      
		    return builder.create();
		    
		case Constants.MANUAL_ADD_MONEY_DIALOG:
			builder = new AlertDialog.Builder(this);
		    // Get the layout inflater
		    inflater = this.getLayoutInflater();

		    // Inflate and set the layout for the dialog
		    // Pass null as the parent view because its going in the dialog layout
		    builder.setView(inflater.inflate(R.layout.add_money_manual, null))
		    // Add action buttons
		           .setPositiveButton("Continue", new DialogInterface.OnClickListener() {
		               @Override
		               public void onClick(DialogInterface dialog, int id) {
		            	   
		            	   AlertDialog alert = (AlertDialog)dialog;
		            	   
		            	   RadioButton addRadioButton = (RadioButton) ((AlertDialog) dialog).findViewById(R.id.addRadioButton);
		            	   
		            	   
		            	   EditText amountText = (EditText)((AlertDialog)dialog).findViewById(R.id.amountText);
		            	   
		            	   int amount = 0;
		            	   try{
		            		   amount = Integer.parseInt(amountText.getText().toString());
		            	   }
		            	   catch(NumberFormatException e){
		            		   
		            	   }
		            	   
		            	   Account account = null;
		            	   
		            	   /** set balance or add money based on radio button **/
		            	   boolean addBalance = false;
		            	   if(addRadioButton.isChecked()) addBalance = true;
		            	   
		            	   if(ViewSavingsActivity.this.accountDBHelper.hasDPSAccount() == false){
		            		   
		            		   account = new Account();
		            		   
		            		   account.name= AccountDBHelper.DPS_ACCOUNT_NAME;
		            		   account.amount = 0;
		            		   
		            		   ViewSavingsActivity.this.accountDBHelper.addAccount(account);
		            	   }
		            	   else{
		            		  account = ViewSavingsActivity.this.accountDBHelper.getDPSAccountAsAccount();
		            	   }
		            	   
		            	   /** if user has input a new amount **/
		            	   if(amount >= 0){
		            		   Log.e("asdf", "amount >= 0");
		            		   if(addBalance){
			            		   /** set the balance because the set balance radio button is checked **/
			            		   account.amount += amount;
			            	   }
			            	   else{
			            		   /** not set balance, add money **/
			            		   account.amount -= amount;
			            	   }
			            	   
			            	   /** update the account in the database **/
			            	   ViewSavingsActivity.this.accountDBHelper.updateAccount(account);

			            	   //ViewSavingsActivity.this.accountDBHelper.updateDPSAmount((int) account.amount);
			            	   ViewSavingsActivity.this.restoreDatabaseValues();
			            	   
			            	   ViewSavingsActivity.this.initHouseAnimation();
			            	   ViewSavingsActivity.this.animateHouse();
		            	   }
		            	   


		               }
		           })
		           .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
		               public void onClick(DialogInterface dialog, int id) {
		                   //LoginDialogFragment.this.getDialog().cancel();
		               }
		           });      
		    return builder.create();
		    
		case Constants.SET_GOAL_DIALOG:
			builder = new AlertDialog.Builder(this);
		    // Get the layout inflater
		    inflater = this.getLayoutInflater();

		    // Inflate and set the layout for the dialog
		    // Pass null as the parent view because its going in the dialog layout
		    builder.setView(inflater.inflate(R.layout.set_goal_dialog_layout, null))
		    // Add action buttons
		           .setPositiveButton("Continue", new DialogInterface.OnClickListener() {
		               @Override
		               public void onClick(DialogInterface dialog, int id) {
		            	   
		            	   AlertDialog alert = (AlertDialog)dialog;
		            	   
		            	   EditText newGoalText = (EditText) alert.findViewById(R.id.savingsGoalText);
		            	   
		            	   try{
		            		   int amount = Integer.parseInt(newGoalText.getText().toString());
		            		   
		            		   	ContentValues values = new ContentValues();
		   						values.put(DBHelper.COLUMN_TOTAL, amount);
		   						dbhelper.updateGoalEntry(values);
		   						
		   						Intent intent = new Intent(ViewSavingsActivity.this, TabRoot.class);
		   						intent.putExtra("START_TAB", "view_savings");
		   						intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		   						ViewSavingsActivity.this.startActivity(intent);
		   					
		            	   }
		            	   catch(NumberFormatException e){
		            		   Toast.makeText(ViewSavingsActivity.this, "invalid number", Toast.LENGTH_LONG).show();
		            	   }
		            	   
		            	   
		            	   
		            	   
		               }
		            	   
		           })
		           .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
		               public void onClick(DialogInterface dialog, int id) {
		                   //LoginDialogFragment.this.getDialog().cancel();
		               }
		           });      
		    return builder.create();
		
		case Constants.SELECT_MODE_DIALOG:
			
//			AlertDialog dialog = new AlertDialog(this);
//			dialog.setContentView(R.layout.choose_mode_layout);
//			
//			ListView list = dialog.findViewById(R.id.listView);
			
			builder = new AlertDialog.Builder(this);
			builder.setCancelable(true)
					.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			               public void onClick(DialogInterface dialog, int id) {
			                   //LoginDialogFragment.this.getDialog().cancel();
			               }
			           })
					.setTitle("You can view your savings on this screen by either:")
					.setItems(R.array.mode_selection_array, new DialogInterface.OnClickListener() {
		               public void onClick(DialogInterface dialog, int which) {
		               // The 'which' argument contains the index position
		               // of the selected item
		            	   if(which == 2){// manual mode is 3rd element in array
		            		   ViewSavingsActivity.this.dbhelper.setMode(DBHelper.MANUAL_MODE);
		            	   }
		            	   else if(which == 1){// manual mode is 3rd element in array
		            		   ViewSavingsActivity.this.dbhelper.setMode(DBHelper.CREATE_ACCOUNT_MODE);
		            		   Intent intent = new Intent(ViewSavingsActivity.this, SetupAccountActivity.class);
		            		   ViewSavingsActivity.this.startActivity(intent);
		            	   }
		            	   else if(which == 0){// manual mode is 3rd element in array
		            		   ViewSavingsActivity.this.dbhelper.setMode(DBHelper.EXISTING_ACCOUNT_MODE);
		            		   Intent intent = new Intent(ViewSavingsActivity.this, LinkExistingAccountActivity.class);
		            		   ViewSavingsActivity.this.startActivity(intent);
		            	   }
		           }
		    });
		    return builder.create();
		    
		case Constants.YODLEE_REFRESH_ERROR:
			builder = new AlertDialog.Builder(this);
			builder.setCancelable(true)
					.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			               public void onClick(DialogInterface dialog, int id) {
			                   //LoginDialogFragment.this.getDialog().cancel();
			               }
			           })
					.setTitle("")
					.setMessage("Your account information was not able to be retrieved.\n\nPlease re-enter your online banking user ID and password.")
					.setPositiveButton("Continue",  new DialogInterface.OnClickListener() {
			               public void onClick(DialogInterface dialog, int id) {
			                   Intent intent = new Intent(ViewSavingsActivity.this, LinkExistingAccountActivity.class);
			                   ViewSavingsActivity.this.startActivity(intent);
			               }
			           });
		    return builder.create();
			
		
		}
		
		return null;
	}
	
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		
		dbhelper = new DBHelper(this);
		
		accountDBHelper = new AccountDBHelper(this);
		
		webHelper = new WebHelper(this);
		
		historyHelper = new HistoryHelper(this);
		
		tipsDBHelper = new TipsDBHelper(this);
		
		this.layoutID = R.layout.view_savings_activity;
		
		changeToLayout(this.layoutID);
		
		initHouseAnimation();
		
		
		
		
		

		


	}
	

	
	public void onResume(){
		super.onResume();
		
		/** make sure account has been created **/
//		if(this.dbhelper.getBoolean(DBHelper.COLUMN_ACCOUNT_CREATED) == false){
//			//redirect to add account page
//			Intent intent = new Intent(ViewSavingsActivity.this, TabRoot.class);
//			intent.putExtra("START_TAB", "add_money");
//			startActivity(intent);
//			return;
//			
//		}
		

			
			int mode = this.dbhelper.getMode();
			
			if(mode == DBHelper.EXISTING_ACCOUNT_MODE){
				this.webHelper.getExistingAccountInfo(false);
				this.handleProgressSpinner();
			}
			else if(mode == DBHelper.CREATE_ACCOUNT_MODE){
				this.webHelper.getAccountInfo(false);
			}
			else if(mode == DBHelper.MANUAL_MODE){
				//handle manual mode
				initHouseAnimation();
				Log.e("on resume", "animating house in on resume");
				animateHouse();
				
			}
			else{
				//select which mode to choose
				
				//create dialog
				this.showDialog(Constants.SELECT_MODE_DIALOG);
			}
			
			
			
			
			
		//}

		
	}
	
	private void handleProgressSpinner() {
		
		//int amount = (int) this.accountDBHelper.getDPSAccountAsAccount().amount;
		
		
		if(this.statusCode == 801){
			/** still loading, show progress bar **/
			
			TableRow progressRow = (TableRow) findViewById(R.id.progressRow);
			progressRow.setVisibility(View.VISIBLE);
			
			TableRow savingsRow = (TableRow) findViewById(R.id.savedRow);
			savingsRow.setVisibility(View.GONE);

		}
		else{
			/** not loading any more, show savings amount **/
			TableRow progressRow = (TableRow) findViewById(R.id.progressRow);
			progressRow.setVisibility(View.GONE);
			
			TableRow savingsRow = (TableRow) findViewById(R.id.savedRow);
			savingsRow.setVisibility(View.VISIBLE);
			
		}
		
	}

	public void onGetAccountInfo(Account[] accounts ){
		
		if(accounts == null || accounts[0] == null){
			
			if(!((Activity) this).isFinishing())
			{
				showDialog(Constants.LOGIN_DIALOG);
			}
			
		}
	
		else{
			if(this.layoutID == R.layout.view_savings_activity){
				
				
				this.accountDBHelper.deleteAll();
				
				for(Account account : accounts){
					this.accountDBHelper.addAccount(account);
				}
				
				
				restoreDatabaseValues();
				
				//addSavingsTip();
				
				animateHouse();
			
			}
			
		}
		
	}
	
	//called after a login thread is executed
	public void onAuthenticate(String username, boolean result){
		
		Log.e("view savings", "called on authenticate");
		
		
		
		if(result == true){
			this.dbhelper.setUsername(username);
			
			if(this.dbhelper.getMode() == DBHelper.CREATE_ACCOUNT_MODE)
				this.webHelper.getAccountInfo(false);
			else if(this.dbhelper.getMode() == DBHelper.CREATE_ACCOUNT_MODE)
				this.webHelper.getExistingAccountInfo(false);
			
			else Log.e("VIEW SAVINGS","no mode selected ");
			
			
			this.webHelper.getUserInfo();
			
			
//			Intent intent = new Intent(this, TabRoot.class);
//			//intent.addFlags(Activity.FLAG_ACTIVITY_CLEAR_TOP);
//			intent.putExtra("START_TAB", "view_savings");
//			startActivity(intent);
			
			//restoreDatabaseValues();
			
			
			//animateHouse();
			
			this.finish();
			
			Intent intent = new Intent(ViewSavingsActivity.this, TabRoot.class);
			intent.putExtra("START_TAB", "view_savings");
			
			this.startActivity(intent);
			
			
		}
		else{
			this.webHelper.logout();
		}
		
		

	}
	
	
	public void onGetTransfers(String result){
		
		if(result == null) return;
		String[] objects = result.split("!!");
		
		/** remove histories sync with website **/
		this.historyHelper.clearHistory();
		
		Transfer[] transfers = new Transfer[objects.length];
		int index = 0;
		
		
		
		
		for(String entry : objects){
			
			JSONObject jsonObject = null;
			try {
				jsonObject = new JSONObject(entry);
				
			} catch (JSONException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
			
			Log.e(tag, entry);	
			Log.e(tag, "***********");
			
			//add parsed account to account DBHelper
			if(jsonObject != null){
			
				try {
					if(jsonObject.has("status") && jsonObject.getString("status").equals("fail")){
						
						//do nothing
						//TODO report error
					}
					else{
						historyHelper.addTransfer(jsonObject);
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				
			
			}

		}
		
		this.addHistoryList();
		
		Runnable runnable = new Runnable() {

	        public void run() {
	        	ViewSavingsActivity.this.updateStatusColorsInHistoryList();
	        }
		};
		Handler handler =  new Handler();
		handler.postDelayed(runnable, 50);

		return;
	}
	
	
	public void onGetExistingAccountInfo(JSONObject json){
		//the given account contains the amount in the users bank account.
		Log.e("onGetExistingAccountINFO", json.toString());
		int statusCode = 0;
		String status = "";
		String message = "";
		try {
			message = json.getString("message");
			status = json.getString("status");
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		try{
			statusCode = json.getInt("statusCode");
			this.statusCode = statusCode;
		}
		catch(JSONException e){
			e.printStackTrace();
		}
		
		if(status.equals("fail")){
			
			if(message.equalsIgnoreCase("must be logged in")){
				showDialog(Constants.LOGIN_DIALOG);
			}
			
			else if(statusCode != 0 && statusCode != 801)
				showDialog(Constants.YODLEE_REFRESH_ERROR);
			
			else{
				Utility.showDialog(this, "You have not linked any accounts!");
			}
			
			
		}
		
		
		
		int savingsAmount = 0;
		try {
			savingsAmount = json.getInt("savings");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
		}
		
		Account account = new Account();

		account.amount = savingsAmount;
		account.name = AccountDBHelper.DPS_ACCOUNT_NAME;
		
		//set the DPS account amount to this account.amount;
		if(account != null){
			Log.e("tag", "On get Existing Account amount = " + account.amount);
			
			
//			if(account.amount < 0){
//				/** still loading, show progress bar **/
//				
//				TableRow progressRow = (TableRow) findViewById(R.id.progressRow);
//				progressRow.setVisibility(View.VISIBLE);
//				
//				TableRow savingsRow = (TableRow) findViewById(R.id.savedRow);
//				savingsRow.setVisibility(View.GONE);
//
//			}
//			else{
//				/** not loading any more, show savings amount **/
//				TableRow progressRow = (TableRow) findViewById(R.id.progressRow);
//				progressRow.setVisibility(View.GONE);
//				
//				TableRow savingsRow = (TableRow) findViewById(R.id.savedRow);
//				savingsRow.setVisibility(View.VISIBLE);
//				
//			}
			
			
			if(this.accountDBHelper.hasDPSAccount()){
				this.accountDBHelper.deleteAll();
				this.accountDBHelper.addYodleeDPSAccount(account);
			}
			else{
				//create the DPS account
				this.accountDBHelper.addYodleeDPSAccount(account);
				
			}
			
			/** refresh the new values in the view **/
			restoreDatabaseValues();
			
			handleProgressSpinner();
			
			
			initHouseAnimation();
			animateHouse();
			
			
			/** if status code = 801, keep refreshing, repeat getExistingAccountInfo() **/
			if(statusCode == 801)
				this.webHelper.getExistingAccountInfo(false);
			
			
			
		}
		else{
			account = new Account();
			account.amount = 0;
			account.name = this.accountDBHelper.DPS_ACCOUNT_NAME;
			
		}

		
	}
	
	
	
	public void restoreDatabaseValues(){
		/** get the ammount saved in the DPS account **/
		int saved = (int) accountDBHelper.getDPSAccountAsAccount().amount;
		
		
		/** get the goal stored in the database helper **/
		int total = (int) dbhelper.selectGoalTotal();
		
		//String deadline = dbhelper.selectGoalDeadline();
		
		TextView goalTotalText = (TextView)findViewById(R.id.goalTotalText);
		TextView goalSavedText = (TextView)findViewById(R.id.goalSavedText);
		TextView bonusPointsValue = (TextView) findViewById(R.id.bonusPointsValue);
		
		goalTotalText.setText("$" + formatter.format(total));
		
		if(saved < 0){
			goalSavedText.setText("$0");
		}
		else goalSavedText.setText("$" + formatter.format(saved));
		
		bonusPointsValue.setText("0");
	}
	
	public void addOnClickListeners(){
		
		if(this.layoutID==R.layout.history_layout){
			
			ImageButton backButton = (ImageButton) findViewById(R.id.backButton);
			
			backButton.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View v) {
					
					changeToLayout(R.layout.view_savings_activity);
					
				}
				
			});
			
			backButton.setOnTouchListener(new OnTouchListener(){
				

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					ImageView image = (ImageView) v;
					
					// TODO Auto-generated method stub
					if(event.getAction() == MotionEvent.ACTION_DOWN){
						image.setImageDrawable(v.getResources().getDrawable(R.drawable.back_btn_clicked));
						rect = new Rect(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
					}
					else if(event.getAction() == MotionEvent.ACTION_UP){
						image.setImageDrawable(v.getResources().getDrawable(R.drawable.back_btn));
					}
					else if(event.getAction() == MotionEvent.ACTION_CANCEL){
						image.setImageDrawable(v.getResources().getDrawable(R.drawable.back_btn));
					}
					
					return false;
				}

			});
			
		}
		
		if(this.layoutID == R.layout.view_savings_activity){
			
			
			FrameLayout redeemPoints = (FrameLayout) findViewById(R.id.viewSavingsRedeemPointsFrameLayout);
			redeemPoints.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View v) {
					Intent intent = new Intent(ViewSavingsActivity.this, BonusPointsActivity.class);
					startActivity(intent);
					
				}
				
			});
			
			
//			redeemPoints.setOnTouchListener(new OnTouchListener(){
//
//				@Override
//				public boolean onTouch(View view, MotionEvent event) {
//					// TODO Auto-generated method stub
//					
//					FrameLayout layout = (FrameLayout) view;
//					
//					ImageView image = (ImageView)layout.findViewById(R.id.backgroundImage);
//					
//					
//					if(event.getAction() == MotionEvent.ACTION_DOWN){
//						image.setImageDrawable(view.getResources().getDrawable(R.drawable.input_field_clicked));
//					}
//					else if(event.getAction() == MotionEvent.ACTION_UP){
//						image.setImageDrawable(view.getResources().getDrawable(R.drawable.input_field));
//					}
//					else if(event.getAction() == MotionEvent.ACTION_CANCEL){
//						image.setImageDrawable(view.getResources().getDrawable(R.drawable.input_field));
//					}
//					
//					
//					return false;
//				}
//				
//			});
			
			LinearLayout setGoalClickable = (LinearLayout) findViewById(R.id.setGoalClickable);
			
			setGoalClickable.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View arg0) {
					
					showDialog(Constants.SET_GOAL_DIALOG);
					
				}
				
			});
			
			
			FrameLayout mortgagePreAppLayout = (FrameLayout) findViewById(R.id.viewSavingsMortgagePreAppFrameLayout);
			
			mortgagePreAppLayout.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View arg0) {
					
					Intent intent = new Intent(ViewSavingsActivity.this, TabRoot.class);
					intent.putExtra("START_TAB", "resources");
					intent.putExtra("viewResource", "mortgagePreApp");
					ViewSavingsActivity.this.startActivity(intent);
					
				}
				
			});
			
			mortgagePreAppLayout.setOnTouchListener(new OnTouchListener(){

				@Override
				public boolean onTouch(View view, MotionEvent event) {
					// TODO Auto-generated method stub
					
					FrameLayout layout = (FrameLayout) view;
					
					ImageView image = (ImageView)layout.findViewById(R.id.backgroundImage);
					
					
					if(event.getAction() == MotionEvent.ACTION_DOWN){
						image.setImageDrawable(view.getResources().getDrawable(R.drawable.input_field_clicked));
					}
					else if(event.getAction() == MotionEvent.ACTION_UP){
						image.setImageDrawable(view.getResources().getDrawable(R.drawable.input_field));
					}
					else if(event.getAction() == MotionEvent.ACTION_CANCEL){
						image.setImageDrawable(view.getResources().getDrawable(R.drawable.input_field));
					}
					
					
					return false;
				}
				
			});
			
			TextView accountSettingsBtn = (TextView) findViewById(R.id.viewSavingAccountSettingsBtnText);
			
			accountSettingsBtn.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					/** TODO temporary link to account setup **/
					
					Intent intent = new Intent(ViewSavingsActivity.this, SettingsActivity.class);
					ViewSavingsActivity.this.startActivity(intent);
					
				}
				
			});
			
			accountSettingsBtn.setOnTouchListener(new OnTouchListener(){

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					// TODO Auto-generated method stub
					
					TextView view = (TextView) v;
					
					//get button root
					FrameLayout root = (FrameLayout) view.getParent().getParent();
					ImageView image = (ImageView) root.getChildAt(0);
					
					
					if(event.getAction() == MotionEvent.ACTION_DOWN){
						image.setImageDrawable(view.getResources().getDrawable(R.drawable.savings_btn_yellow_clicked));
						rect = new Rect(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
					}
					else if(event.getAction() == MotionEvent.ACTION_UP){
						image.setImageDrawable(view.getResources().getDrawable(R.drawable.savings_btn_yellow));
					}
					else if(event.getAction() == MotionEvent.ACTION_CANCEL){
						image.setImageDrawable(view.getResources().getDrawable(R.drawable.savings_btn_yellow));
					}
					
					
					return false;
				}
				
			});
			
			TextView addMoneyBtn = (TextView) findViewById(R.id.viewSavingsAddMoneyBtnText);
			
			addMoneyBtn.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View v) {
					
					if(ViewSavingsActivity.this.dbhelper.getMode() == DBHelper.MANUAL_MODE){
						
						/** show manual add money dialog **/
						showDialog(Constants.MANUAL_ADD_MONEY_DIALOG);
						
					}
					else{
						Log.e("View Savings", "Clicked 'Add Money' button");
						Intent intent = new Intent(ViewSavingsActivity.this, TabRoot.class);
						//Log.d("Main Activity", "Starting Mortgage Calc Activity");
						intent.putExtra("START_TAB", "add_money");
						ViewSavingsActivity.this.startActivity(intent);
					}
					
					
				}
				
			});
			
			addMoneyBtn.setOnTouchListener(new OnTouchListener(){

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					// TODO Auto-generated method stub
					
					TextView view = (TextView) v;
					
					//get button root
					FrameLayout root = (FrameLayout) view.getParent().getParent();
					ImageView image = (ImageView) root.getChildAt(0);
					
					if(event.getAction() == MotionEvent.ACTION_DOWN){
						image.setImageDrawable(view.getResources().getDrawable(R.drawable.savings_btn_blue_clicked));
					}
					else if(event.getAction() == MotionEvent.ACTION_UP){
						image.setImageDrawable(view.getResources().getDrawable(R.drawable.savings_btn_blue));
					}
					else if(event.getAction() == MotionEvent.ACTION_CANCEL){
						image.setImageDrawable(view.getResources().getDrawable(R.drawable.savings_btn_blue));
					}
					
					return false;
				}
				
			});
			
			
			TextView historyBtn = (TextView) findViewById(R.id.viewSavingHistoryBtnText);
			
			historyBtn.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View v) {
					Log.e("View Savings", "Clicked 'History' button");
					
					/** TODO change layout to view_history **/
					
					changeToLayout(R.layout.history_layout);
					
				}
				
			});
			
			historyBtn.setOnTouchListener(new OnTouchListener(){

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					// TODO Auto-generated method stub
					
					TextView view = (TextView) v;
					
					//get button root
					FrameLayout root = (FrameLayout) view.getParent().getParent();
					ImageView image = (ImageView) root.getChildAt(0);
					
					if(event.getAction() == MotionEvent.ACTION_DOWN){
						image.setImageDrawable(view.getResources().getDrawable(R.drawable.savings_btn_orange_clicked));
					}
					else if(event.getAction() == MotionEvent.ACTION_UP){
						image.setImageDrawable(view.getResources().getDrawable(R.drawable.savings_btn_orange));
					}
					else if(event.getAction() == MotionEvent.ACTION_CANCEL){
						image.setImageDrawable(view.getResources().getDrawable(R.drawable.savings_btn_orange));
					}
					
					return false;
				}
				
			});
			
			TextView withdrawalBtn = (TextView) findViewById(R.id.viewSavingWithdrawalBtnText);
			
			withdrawalBtn.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View v) {
					Log.e("View Savings", "Clicked 'Withdrawal' button");
					
					/** TODO change layout to view_history **/
					
					Intent intent = new Intent(ViewSavingsActivity.this, TabRoot.class);
					intent.putExtra("START_TAB", "add_money");
					ViewSavingsActivity.this.startActivity(intent);
					
				}
				
			});
			
			
			withdrawalBtn.setOnTouchListener(new OnTouchListener(){

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					// TODO Auto-generated method stub
					
					TextView view = (TextView) v;
					
					//get button root
					FrameLayout root = (FrameLayout) view.getParent().getParent();
					ImageView image = (ImageView) root.getChildAt(0);
					
					if(event.getAction() == MotionEvent.ACTION_DOWN){
						image.setImageDrawable(view.getResources().getDrawable(R.drawable.savings_btn_purple_clicked));
					}
					else if(event.getAction() == MotionEvent.ACTION_UP){
						image.setImageDrawable(view.getResources().getDrawable(R.drawable.savings_btn_purple));
					}
					else if(event.getAction() == MotionEvent.ACTION_CANCEL){
						image.setImageDrawable(view.getResources().getDrawable(R.drawable.savings_btn_purple));
					}
					
					return false;
				}
				
			});
			
		}
		
		
	}
	
	
	/** init house animation **/
	public void initHouseAnimation(){
		
		ImageView emptyView = (ImageView)findViewById(R.id.house_empty);
		ImageView fullView = (ImageView)findViewById(R.id.house_full);
		TextView percentageText = (TextView) findViewById(R.id.percentageValue);
		
		fullView.setImageBitmap(null);
		
		Bitmap empty = BitmapFactory.decodeResource(getResources(),R.drawable.savings_house_empty);
		emptyView.setImageBitmap(empty);
		
		percentageText.setText("%0");
		
	}
	
	/**
	 * fills the house image, based on the amount saved
	 */
	@SuppressLint("NewApi")
	public void animateHouse(){
		
		
		int currentapiVersion = android.os.Build.VERSION.SDK_INT;
		if (currentapiVersion >= android.os.Build.VERSION_CODES.HONEYCOMB){
		    // Do something for froyo and above versions
			this.animateHouseTask = new AnimateHouseTask().executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
		} else{
		    // do something for phones running an SDK before froyo
			this.animateHouseTask = new AnimateHouseTask().execute();
		}
		
//		TextView moneySavedText = (TextView) findViewById(R.id.goalSavedText);
//		TextView downPaymentGoalText = (TextView)findViewById(R.id.goalTotalText);
//		
//		double goal = Integer.parseInt(downPaymentGoalText.getText().toString().replace("$", "").replace(",", ""));
//		
//		savedTotal = 0;
//		try{
//			savedTotal = Integer.parseInt(moneySavedText.getText().toString().replace("$", "").replace(",", ""));
//		}
//		catch(NumberFormatException e){
//			
//		}
//
//		/** this is the place holder for saved. will grow until reaches saved value. This animates the house **/
//		int savedGrowing = 0;
//		
//		ImageView emptyView = (ImageView)findViewById(R.id.house_empty);
//		ImageView fullView = (ImageView)findViewById(R.id.house_full);
//		TextView percentageText = (TextView) findViewById(R.id.percentageValue);
//		
//		if(goal == 0 || savedTotal == 0 || goal < 0 || savedTotal < 0){
//			// Assign new bitmap to ImageView
//			
//			fullView.setImageDrawable(null);
//			emptyView.setImageDrawable(getResources().getDrawable(R.drawable.savings_house_empty));
//			
//			percentageText.setText("0%");
//			
//		}
//
//		else{
//			
//			percentTotal = savedTotal/goal;
//			
//			double percent = 0;
//			
//			
//			while(percent < percentTotal){
//				
//				//skip the loop
//				percent = percentTotal;
//				//percent += .01;
//				
//				//adjust the percent and change the image accordingly
//				
//				if(percent >= 1){
//					
//					fullView.setImageDrawable(getResources().getDrawable(R.drawable.savings_house_full));
//
//					emptyView.setImageDrawable(null);
//					
//					percentageText.setText("100%");
//				}
//				else{
//					/** set the percentage of the house completed to the Text View **/
//					
//					
//					int percentInt = (int) (percent*100);
//					percentageText.setText(percentInt + "%");
//					
//					// Set some constants
//					final Bitmap empty = BitmapFactory.decodeResource(getResources(),R.drawable.savings_house_empty);
//					final int empty_x = 0;
//					final int empty_y = 0;
//					final int empty_px = empty.getWidth();
//					int empty_py = (int) (empty.getHeight()*(1-percent));
//					
//					final Bitmap full = BitmapFactory.decodeResource(getResources(),R.drawable.savings_house_full);
//					final int full_x = 0;
//					final int full_y = empty_py;
//					final int full_px = full.getWidth();
//					final int full_py = (int) (full.getHeight()*(percent));
//
//					// Crop bitmap
//					
//					Bitmap emptyBitmap = Bitmap.createBitmap(empty, empty_x, empty_y, empty_px, empty_py, null, false);
//					
//					Log.e("animate house", "y = " + full_y + "height = " + full_py);
//					Bitmap fullBitmap = null;
//					if(full_py > 0){
//						 fullBitmap = Bitmap.createBitmap(full, full_x, full_y, full_px, full_py, null, false);
//					}
//
//					// Assign new bitmap to ImageView
//
//					emptyView.setImageBitmap(emptyBitmap);
//					
//					fullView.setImageBitmap(fullBitmap);
//				}
//
//				
//			}
//			
//			
//
//		}

	}
	
	

	private int dpToPx(int dp)
	{
	    float density = getApplicationContext().getResources().getDisplayMetrics().density;
	    return Math.round((float)dp * density);
	}
	
	public void changeToLayout(int layout){
		
		this.layoutID = layout;
		
		this.setContentView(layout);
		
		
		if(layout == R.layout.view_savings_activity){
			
			
			
			restoreDatabaseValues();
			
			if(this.dbhelper.getMode() == DBHelper.EXISTING_ACCOUNT_MODE){

			}
			
			if(this.dbhelper.getMode() == DBHelper.MANUAL_MODE){
//				initHouseAnimation();
//				animateHouse();
			}
			
			addSavingsTip();
			
			
			
		}
		else if(layout == R.layout.history_layout){
			
			
			
			this.webHelper.getTransfers();
			//addHistoryList();
			
			
			updateStatusColorsInHistoryList();
			
		}


		addOnClickListeners();
		
		
	}

	
	/**
	 * adds the transaction history to the listview in the activity
	 */
	public void addHistoryList(){
		Cursor cursor = historyHelper.getHistoryAsCursor();
		
		/** if there are Recurring Transfers **/
		/** add recurring transfers view **/
		if(cursor.moveToFirst()){

			
			ListView historyList = (ListView) findViewById(R.id.historyListView);
			historyList.setDivider(null);
			historyList.setDividerHeight(0);
			
			
			

			String[] fromColumns = {HistoryHelper.COLUMN_FROM, HistoryHelper.COLUMN_TO, HistoryHelper.COLUMN_AMOUNT, HistoryHelper.COLUMN_DATE_SUBMITTED, HistoryHelper.COLUMN_STATUS};
			
			int[] toViews = { R.id.historyItemFrom, R.id.historyItemTo, R.id.historyItemAmount, R.id.historyItemDate, R.id.historyItemStatus};

			
			
			SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, 
			        R.layout.history_layout_list_item, cursor, fromColumns, toViews, 0);
			
			
			
			int count = historyList.getChildCount();
			
			
			
			Log.e(tag, "START UPDATE STATUS COLOR : CHILD = " + historyList.getChildCount());
			/** update status colors **/
			for(int i = 0;  i < count; i++){
				
				View item = historyList.getChildAt(i);
				
				TextView statusText = (TextView) item.findViewById(R.id.historyItemStatus);
				
				Log.e(tag, "status text = " + statusText.getText());
				
				if(statusText.getText().toString().equalsIgnoreCase("Pending")){
					Log.e(tag, "CHANGING STATUS COLOR IN HISTORY ");
					statusText.setTextColor(Color.GRAY);
				}
				if(statusText.getText().toString().equalsIgnoreCase("Completed")){
					statusText.setTextColor(Color.GREEN);
				}
				if(statusText.getText().toString().equalsIgnoreCase("Failed")){
					statusText.setTextColor(Color.RED);
				}
				
			}
			
			historyList.setAdapter(adapter);
			
			//Utility.setListViewHeightBasedOnChildren(historyList);
		}
	}
	
	public void addSavingsTip(){
		
		/** Insert Tips Table **/
		this.tipsTable = (TableLayout) findViewById(R.id.tipsTable);
		
		this.tipsTable.removeAllViews();
		
		LayoutInflater layoutInflater = (LayoutInflater) 
		        this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
		
		
		tipsTable.addView(layoutInflater.inflate(R.layout.tips_layout, tipsTable, false )); 
		/**********************/
		
		TextView titleText = (TextView) this.tipsTable.findViewById(R.id.tipTitle);
		
		TextView tipText = (TextView) this.tipsTable.findViewById(R.id.tipText);
		
		Tip tip = this.tipsDBHelper.getTip();
		
		if(tip != null){
			titleText.setText(tip.title);
			tipText.setText(tip.text);
		}
		else Log.e("null tip", "null tip");
		

		
	}
	
	
	
	
	public void updateStatusColorsInHistoryList(){
		
		ListView historyList = (ListView) findViewById(R.id.historyListView);
		
		
		
		if(historyList != null){
			
			Log.e(tag, "START UPDATE STATUS COLOR : CHILD = " + historyList.getChildCount());
			/** update status colors **/
			for(int i = 0;  i < historyList.getChildCount(); i++){
				
				View item = historyList.getChildAt(i);
				
				TextView statusText = (TextView) item.findViewById(R.id.historyItemStatus);
				
				Log.e(tag, "status text = " + statusText.getText());
				
				if(statusText.getText().toString().equalsIgnoreCase("Pending")){
					Log.e(tag, "CHANGING STATUS COLOR IN HISTORY ");
					statusText.setTextColor(Color.GRAY);
				}
				if(statusText.getText().toString().equalsIgnoreCase("Completed")){
					statusText.setTextColor(Color.parseColor("#2B9605"));
				}
				if(statusText.getText().toString().equalsIgnoreCase("Failed")){
					statusText.setTextColor(Color.RED);
				}
				
			}
		}
		
		
	}


	public void onGetUserInfo(JSONObject json) {
		// TODO Auto-generated method stub

		try {
			String username = json.getString("username");
			String email = json.getString("email");
			String password = json.getString("password");
			int mode = json.getInt("mode");
			int achConfirmed = json.getInt("achConfirmed");
			
			
			Log.e("ongetUserInfo View Savings", "mode = " + mode);
			
			this.dbhelper.setColumnString(DBHelper.COLUMN_USERNAME, username);
			this.dbhelper.setColumnString(DBHelper.COLUMN_EMAIL, email);
			this.dbhelper.setColumnString(DBHelper.COLUMN_PASSWORD, password);
			
			this.dbhelper.setMode(mode);
			this.dbhelper.setBoolean(DBHelper.COLUMN_ACH_CONFIRMED, achConfirmed);
			
			
			
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
	
	class AnimateHouseTask extends AsyncTask<Void, Bitmap, Bitmap>{
		
		
		int currentPercent = 0;
		
		double percent = 0;
		
		@Override
		protected void onPreExecute(){
			Log.e("AnimateHouseTask", "starting to animate");
			
			initHouseAnimation();
		}

		@Override
		protected Bitmap doInBackground(Void... arg0) {
			TextView moneySavedText = (TextView) findViewById(R.id.goalSavedText);
			TextView downPaymentGoalText = (TextView)findViewById(R.id.goalTotalText);
			
			double goal = Integer.parseInt(downPaymentGoalText.getText().toString().replace("$", "").replace(",", ""));
			
			savedTotal = 0;
			try{
				savedTotal = Integer.parseInt(moneySavedText.getText().toString().replace("$", "").replace(",", ""));
			}
			catch(NumberFormatException e){
				
			}

			/** this is the place holder for saved. will grow until reaches saved value. This animates the house **/
			int savedGrowing = 0;
			
			ImageView emptyView = (ImageView)findViewById(R.id.house_empty);
			ImageView fullView = (ImageView)findViewById(R.id.house_full);
			TextView percentageText = (TextView) findViewById(R.id.percentageValue);
			
			if(goal == 0 || savedTotal == 0 || goal < 0 || savedTotal < 0){
				
				Log.e("animateHouseTask", "goal/SavedTotal < = 0");
				
				return null;
				
			}

			else{
				
				percentTotal = savedTotal/goal;
				
				this.percent = 0;
				
				
				while(percent < percentTotal){
					
					
					//if task is cancelled, quit
					if(isCancelled()) return null;
					
					
					//skip the loop
					//percent = percentTotal;
					percent += .03;
					
					//adjust to proper value if increment is above total
					if(percent >= percentTotal) percent = percentTotal;
					
					this.currentPercent = (int) (percent*100);
					
					//adjust the percent and change the image accordingly
					
					if(percent >= 1){

						Bitmap full = BitmapFactory.decodeResource(getResources(),R.drawable.savings_house_full);
						
						publishProgress(null, full);

					}
					else{
						/** set the percentage of the house completed to the Text View **/
						
						
						// Set some constants
						final Bitmap empty = BitmapFactory.decodeResource(getResources(),R.drawable.savings_house_empty);
						final int empty_x = 0;
						final int empty_y = 0;
						final int empty_px = empty.getWidth();
						int empty_py = (int) (empty.getHeight()*(1-percent));
						
						final Bitmap full = BitmapFactory.decodeResource(getResources(),R.drawable.savings_house_full);
						final int full_x = 0;
						final int full_y = empty_py;
						final int full_px = full.getWidth();
						final int full_py = (int) (full.getHeight()*(percent));

						// Crop bitmap
						
						Bitmap emptyBitmap = Bitmap.createBitmap(empty, empty_x, empty_y, empty_px, empty_py, null, false);
						
						Log.e("animate house", "y = " + full_y + "height = " + full_py);
						Bitmap fullBitmap = null;
						if(full_py > 0){
							 fullBitmap = Bitmap.createBitmap(full, full_x, full_y, full_px, full_py, null, false);
						}

						// Assign new bitmap to ImageView

						
						publishProgress(emptyBitmap, fullBitmap);
						//emptyView.setImageBitmap(emptyBitmap);
						
						//fullView.setImageBitmap(fullBitmap);
					}

					
				}

			}
			return null;
			
		}
		
		@Override
		protected void onProgressUpdate(Bitmap... images){
			
			Log.e("animateHouseTask", "publishing Progress. animate House");
			
			Bitmap full = images[1];
			Bitmap empty = images[0];
			
			ImageView emptyView = (ImageView)findViewById(R.id.house_empty);
			ImageView fullView = (ImageView)findViewById(R.id.house_full);
			TextView percentageText = (TextView) findViewById(R.id.percentageValue);
			
			fullView.setImageBitmap(full);
			emptyView.setImageBitmap(empty);
			
			if(this.percent >= 1)
				percentageText.setText("%100");
			else
				percentageText.setText("%"+this.currentPercent);
			
		}
		
		
		void onPostExecute(Bitmap... images){ 
			
			Log.e("AnimateHouseTask", "done animating house");
			ImageView emptyView = (ImageView)findViewById(R.id.house_empty);
			ImageView fullView = (ImageView)findViewById(R.id.house_full);
			TextView percentageText = (TextView) findViewById(R.id.percentageValue);
			
			if(images[0] == null && images[1] == null){
				//fullView.setImageBitmap(null);
				//emptyView.setImageDrawable(getResources().getDrawable(R.drawable.savings_house_empty));
			}
		}
		
	}
	
	
	
}
